<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医生姓名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入医生姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生状态" prop="status" style="width: 300px">
        <el-select v-model="queryParams.status" placeholder="请选择医生状态" clearable>
          <el-option
              :value="item.value"
              v-for="(item, index) in status"
              :key="index"
              :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="医生院区" prop="hospitalArea" style="width: 300px">
        <el-select v-model="queryParams.hospitalArea" placeholder="请选择医生院区" clearable>
          <el-option
              :value="item.value.campusName"
              v-for="(item, index) in hospitalsList"
              :key="index"
              :label="item.label.campusName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="医生职务" prop="title" style="width: 300px">
        <el-select v-model="queryParams.title" placeholder="请选择医生职务" clearable>
          <el-option
              v-for="dict in doctorposition" :key="dict.value" :label="dict.label" :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="科室名称" prop="department">
        <el-select
            v-model="queryParams.department"
            placeholder="请输入科室名称"
            clearable
            filterable
        >
          <el-option
              v-for="item in departmentOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:doctors:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:doctors:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:doctors:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:doctors:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="doctorsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="医生ID" align="center" prop="id"/>
      <el-table-column label="医生姓名" align="center" prop="name"/>
      <el-table-column label="医生头像" align="center" prop="avatar" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="所属院区" align="center" prop="hospitalArea"/>
      <el-table-column label="职称" align="center" prop="title"/>
      <el-table-column label="科室" align="center" prop="department"/>
      <el-table-column label="标签" align="center" prop="tags"/>
      <el-table-column label="医生简介" align="center" prop="introduction"/>
      <el-table-column label="挂号费" align="center" prop="bookingFee"/>
      <el-table-column label="诊查费" align="center" prop="consultFee"/>
      <el-table-column label="医生状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:doctors:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:doctors:remove']">删除
          </el-button>
          <el-button link type="primary" icon="download" @click="handdownload(scope.row)"
                     v-hasPermi="['system:doctors:remove']">下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改医生信息对话框 -->
    <el-dialog :title="title1" v-model="open" width="500px" append-to-body>
      <el-form ref="doctorsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医生姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入医生姓名"/>
        </el-form-item>
        <el-form-item label="医生头像" prop="avatar">
          <image-upload v-model="form.avatar"/>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="form.tags" placeholder="请输入标签"/>
        </el-form-item>
        <el-form-item label="医生简介" prop="introduction">
          <el-input v-model="form.introduction" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="挂号费" prop="bookingFee">
          <el-input v-model="form.bookingFee" placeholder="请输入挂号费"/>
        </el-form-item>
        <el-form-item label="职务" prop="title">
          <el-select v-model="form.title" placeholder="请选择职务" clearable :style="{width: '100%'}">
            <el-option v-for="dict in doctorposition" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="院区" prop="hospitalArea">
          <el-select v-model="form.hospitalArea" placeholder="请选择院区" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in hospitalsList" :key="index" :label="item.label.campusName"
                       :value="item.value.campusName" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="department">
          <el-select v-model="form.department" placeholder="请选择科室" clearable :style="{width: '100%'}" :disabled="!form.hospitalArea">
            <el-option
                :value="item"
                v-for="item in department"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="诊查费" prop="consultFee">
          <el-input v-model="form.consultFee" placeholder="请输入诊查费"/>
        </el-form-item>
        <el-form-item label="医生状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="(item, index) in status"
                :key="index"
                :label="item.label"
            >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Doctors">
import {listDoctors, getDoctors, delDoctors, addDoctors, updateDoctors,download} from "@/api/system/doctors"
import {listCampus} from "@/api/system/package.js";
import { getDepartmentNames ,getDepartmentsByhospitalArea} from "@/api/system/departments";

const {proxy} = getCurrentInstance()
const {doctorposition} = proxy.useDict('doctorposition')

const doctorsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title1 = ref()
const hospitalsList = ref([])

const departmentOptions = ref([])

const status = ref([{
  "label": "上班",
  "value": "上班"
}, {
  "label": "休假",
  "value": "休假"
}])
let department = ref([])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    hospitalArea: null,
    title: null,
    department: null,
    tags: null,
    status: null,
    avatar:''
  },
  rules: {
    name: [
      {required: true, message: "医生姓名不能为空", trigger: "blur"}
    ],
    hospitalArea: [
      {required: true, message: "所属院区不能为空", trigger: "change"}
    ],
    title: [
      {required: true, message: "职称不能为空", trigger: "change"}
    ],
    department: [
      {required: true, message: "科室不能为空", trigger: "change"}
    ],
    tags: [
      {required: true, message: "标签不能为空", trigger: "blur"}
    ],
    introduction: [
      {required: true, message: "医生简介不能为空", trigger: "blur"}
    ],
    bookingFee: [
      {required: true, message: "挂号费不能为空", trigger: "blur"}
    ],
    consultFee: [
      {required: true, message: "诊查费不能为空", trigger: "blur"}
    ],
    status: [
      {required: true, message: "医生状态不能为空", trigger: "change"}
    ]
  }
})

const {queryParams, form, rules} = toRefs(data)

// 获取科室名称列表
function getDepartmentOptions() {
  getDepartmentNames().then(response => {
    departmentOptions.value = response.data
  })
}
import { watch } from 'vue';

// 在 setup 中添加 watch
watch(() => form.value.hospitalArea, (newValue, oldValue) => {
  console.log('hospitalArea changed:', newValue);
  // 在这里执行你想要的操作，比如根据新的院区获取对应的科室
  if (newValue) {
    getDepartmentNames(newValue).then(response => {
      department.value = response.data;
      getDepartmentsByhospitalArea(newValue).then(response => {
        console.log(response)
         department = [];
        for (var i = 0; i < response.length; i++){
          department.push(response[i].departmentName)
        }
      })
    });
  }
});
/** 查询医生信息列表 */
function getList() {
  loading.value = true
  getDepartmentNames().then(response => {
    department=response.data
  })
  listDoctors(queryParams.value).then(response => {
    doctorsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
getlistCampus()
//获取所有院区
function getlistCampus(){
  listCampus().then(response => {
    hospitalsList.value = Array.isArray(response)
        ? response.map(item => ({ label: item, value: item }))
        : [];
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    avatar: null,
    hospitalArea: null,
    title: null,
    department: null,
    tags: null,
    introduction: null,
    bookingFee: null,
    consultFee: null,
    status: null
  }
  proxy.resetForm("doctorsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title1.value = "添加医生信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getDoctors(_id).then(response => {
    form.value = response.data
    open.value = true
    title1.value = "修改医生信息"
  })
  getDepartmentsByhospitalArea(row.hospitalArea).then(response => {
     department = [];
    for (var i = 0; i < response.length; i++){
      department.push(response[i].departmentName)
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["doctorsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDoctors(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDoctors(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除医生信息编号为"' + _ids + '"的数据项？').then(function () {
    return delDoctors(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}
//下载图片
function handdownload(row) {
  var url=row.avatar
  const avatar = url.split('/').pop().split('?')[0]
  proxy.download('common/download/resource', {
    resource:avatar
  }, `${new Date().getTime()}.png`)
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/doctors/export', {
    ...queryParams.value
  }, `doctors_${new Date().getTime()}.xlsx`)
}
getList()
onActivated(()=>{
  getDepartmentOptions()
  getList()
})

</script>
